package com.example.springbootmodel.Utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class Base64ImgUtil {

	/***
	 * @description: 将base64编码字符串转换为图片
	 * @param: imgStr base64编码字符串
			   path 图片路径-具体到文件
	 * @return: boolean
	 * @author: ym
	 * @date: 21/12/27 10:36
	 */
	@SuppressWarnings("restriction")
	public static boolean generateImage(String imgStr, String path) throws IOException{
		if (imgStr == null || "".equals(imgStr)){
			return false;
		}
		// 移除前缀
		if(imgStr.startsWith("data:")){
			imgStr = imgStr.split(",")[1];
		}
		BASE64Decoder decoder = new BASE64Decoder();
		try (OutputStream out = new FileOutputStream(path)){
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			File fileParent = new File(path).getParentFile();
			if (!fileParent.exists()) {
				fileParent.mkdirs();
			}
			out.write(b);
			out.flush();
			return true;
		}
	}

	/***
	 * @description: 根据图片地址转换为base64编码字符串
	 * @param: imgFile
	 * @return: java.lang.String
	 * @author: ym
	 * @date: 21/12/27 10:36
	 */
	@SuppressWarnings("restriction")
	public static String getImageStr(String imgFile) throws IOException{
		try (InputStream inputStream = new FileInputStream(imgFile)){
			byte[] data = new byte[inputStream.available()];
			inputStream.read(data);
			return new BASE64Encoder().encode(data);
		}
	}
}
